package m.store.service;

import m.base.model.GoodsInfo;
import m.base.model.StoreInfo;
import m.base.util.PowerUtil;
import m.common.model.util.*;
import m.common.service.Service;
import m.store.model.*;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StoreGoodsService extends Service {
    public String doSave(StoreGoods model) throws Exception {
        String msg="";
        model.setStore(PowerUtil.getSessionStore(true));
        ModelCheckUtil.checkNotNull(model,"name","property");
        ModelCheckUtil.checkUniqueCombine(model, new String[]{"name", "store.oid"}, "商品名称已存在");
        if(StringUtil.isSpace(model.getAttrJson())) model.setAttrJson("[]");
        if(ObjectUtil.isEmptyOid(model)){
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
            if(model.getProperty().equals(StoreGoods.Property_Server)){
                addServerStock(model);
            }
            msg="保存成功";
        }else {
            StoreGoods goods = ModelQueryList.getModel(StoreGoods.class, model.getOid(), "*");
            if (ObjectUtil.notEmptyOid(goods.getGoods())) throw new MException(this.getClass(), "引用商品不能修改");
            PowerUtil.verifyStoreData(goods.getStore().getOid());
            getService(StoreGoodsHistoryService.class).save(goods);
            ModelUpdateUtil.updateModel(model,"name","typeName","factoryName","attrJson","offerPrice","storeType.oid");
            msg="修改成功";
        }
        return msg;
    }
    public StoreGoods copyGoodsInfo(StoreInfo store,GoodsInfo goods) throws SQLException, MException {
        StoreGoods model= ModelQueryList.getModel(StoreGoods.class,new String[]{"*"},
            QueryCondition.and(
                    QueryCondition.eq("store.oid",store.getOid()),
                    QueryCondition.eq("goods.oid",goods.getOid())
            )
        );
        if(null==model){
            model=new StoreGoods();
            model.setStore(store);
            model.setGoods(goods);
            model.setTypeName(goods.getTypeName());
            model.setFactoryName(goods.getFactoryName());
            model.setName(goods.getName());
            model.setAttrJson(goods.getAttrJson());
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
        }
        return model;
    }
    public void syncAttrJson(GoodsInfo goods) throws SQLException, MException {
        if(ObjectUtil.isEmptyOid(goods)) return;
        List<StoreGoods> ls=ModelQueryList.getModelList(StoreGoods.class,new String[]{"*"},null,
                QueryCondition.eq("oid",goods.getOid()));
        ls.forEach(item->{
            item.setName(goods.getName());
            item.setAttrJson(goods.getAttrJson());
        });
        if(!ls.isEmpty()){
            ModelUpdateUtil.updateModels(ls.toArray(new StoreGoods[0]),"name","attrJson");
        }
    }
    public void addServerStock(StoreGoods goods) throws Exception {
        String guestOid=PowerUtil.getSelfGuestInfo().getOid();
        List<StockInfo> ls= ModelQueryList.getModelList(StockInfo.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("guest.oid",guestOid),
                QueryCondition.eq("type",StockInfo.Type_Server)
            )
        );
        StockInfo model;
        if(!ls.isEmpty()) {
            model=ls.get(0);
        }else{
            model=new StockInfo();
            model.setOid(GenerateID.generatePrimaryKey());
            model.setType(StockInfo.Type_Server);
            model.setStatus(OrderModel.Status_Done);
            model.setGuest(new GuestInfo());
            model.getGuest().setOid(guestOid);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setStore(PowerUtil.getSessionStore(true));
            ModelUpdateUtil.insertModel(model);
        }
        GoodsStockRecord record=ModelQueryList.getModel(GoodsStockRecord.class,new String[]{"*"},
            QueryCondition.and(
                QueryCondition.eq("goods.oid",goods.getOid()),
                QueryCondition.eq("stock.oid",model.getOid())
            )
        );
        if(null==record) {
            record=new GoodsStockRecord();
            record.setOid(GenerateID.generatePrimaryKey());
            record.setStore(PowerUtil.getSessionStore(true));
            record.setStock(model);
            record.setOperDate(new Date());
            record.setGoods(goods);
            ModelUpdateUtil.insertModel(record);
        }
    }
    public void updateServerStockNum(String goodsOid) throws MException {
        ModelUpdate.init(GoodsStockRecord.class)
        .set("stockNum",GoodsOutRecord.class, "ifnull(sum(#{num}),0)",
            QueryCondition.and(
                QueryCondition.eq("goods.oid", goodsOid),
                QueryCondition.in("sale.status", OrderModel.Status_Done)
            )
        )
        .execute(QueryCondition.eq("goods.oid",goodsOid));
    }
}
